<template>
	<view>
		<view class="charts-box">
			<qiun-data-charts type="line" :opts="temperatureOpts" :chartData="temperatureData" :ontouch="true" />
		</view>
		<view class="charts-box">
			<qiun-data-charts type="line" :opts="humidityOpts" :chartData="humidityData" :ontouch="true" />
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// temperature 数据
				temperatureData: {},
				// humidity 数据
				humidityData: {},
				// 图表配置参数
				temperatureOpts: {
					color: ["#FC8452"],
					padding: [15, 10, 0, 15],
					enableScroll: true, // 开启滚动

					xAxis: {
						disableGrid: true,
						itemCount: 6, // 设置单屏幕显示的数据点数量
						scrollShow: true, // 显示滚动条
						scrollAlign: "right", // 滚动条初始位置
					},
					yAxis: {
						gridType: "dash",
						dashLength: 2,
					},
					extra: {
						// 折线图的配置
						line: {
							type: "curve", // 折线图类型，圆滑
							width: 2, // 折线的宽度
							activeType: "hollow", // 空心点
						},
					},
				},
				humidityOpts: {
					color: ["#1890FF"],
					padding: [15, 10, 0, 15],
					enableScroll: true, // 开启滚动
					xAxis: {
						disableGrid: true,
						itemCount: 6, // 设置单屏幕显示的数据点数量
						scrollShow: true, // 显示滚动条
						scrollAlign: "right", // 滚动条初始位置
					},
					yAxis: {
						gridType: "dash",
						dashLength: 2,
					},
					extra: {
						line: {
							type: "curve",
							width: 2,
							activeType: "hollow",
						},
					},
				},
			};
		},
		created() {
			this.getDateByDate();


			// this.getServerData();

			// 模拟每隔一段时间加入新的数据
			// setInterval(() => {
			// 	this.addNewData();
			// }, 2000);
		},
		methods: {
			getCurrentTime(date) {
				// 获取当前日期
				let currentDate;
				if (date == null) {
					currentDate = new Date();
				} else {
					currentDate = date;
				}


				// 获取年、月、日
				let year = currentDate.getFullYear();
				let month = (currentDate.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始计数的，需要加1
				let day = currentDate.getDate().toString().padStart(2, '0');

				// 格式化今天的日期时间为00:00:00
				let todayFormattedDateTime = `${year}-${month}-${day} 00:00:00`;

				// 获取明天的日期
				let tomorrowDate = new Date(currentDate);
				tomorrowDate.setDate(currentDate.getDate() + 1);

				// 获取年、月、日
				let tomorrowYear = tomorrowDate.getFullYear();
				let tomorrowMonth = (tomorrowDate.getMonth() + 1).toString().padStart(2, '0');
				let tomorrowDay = tomorrowDate.getDate().toString().padStart(2, '0');

				// 格式化明天的日期时间为00:00:00
				let tomorrowFormattedDateTime = `${tomorrowYear}-${tomorrowMonth}-${tomorrowDay} 00:00:00`;

				// 返回包含今天和明天的日期的数组
				return [todayFormattedDateTime, tomorrowFormattedDateTime];
			},
			//父组件中的日期更新，重新请求
			getDateByDate(date) {
				//1.从服务器拿数据
				//1.1拿到设备id
				let deviceId;
				try {
					deviceId = uni.getStorageSync('deviceId');

				} catch (e) {
					// error
					console.log(e.message)
				}
				deviceId = parseInt(deviceId, 10);

				//获取当前日期
				let dates = this.getCurrentTime(date);

				//1.2带着deviceId请求温湿度历史数据
				uni.request({
					url: `${this.$store.state.ipAddr}/historyState`, //仅为示例，并非真实接口地址。
					data: {
						deviceId: deviceId,
						startTime: dates[0],
						endTime: dates[1]
					},
					success: (res) => {
						let data = res.data.data

						let temperatureRes = {
							categories: [],
							series: [{
								name: "温度",
								data: [],
							}],
						};

						let humidityRes = {
							categories: [],
							series: [{
								name: "湿度",
								data: [],
							}],
						};

						for (const item of data) {

							let createTimeArray = item.createTime.toString().split(' ')


							// Assuming item.createTime is in a suitable format for categories
							temperatureRes.categories.push(createTimeArray[1]);
							humidityRes.categories.push(createTimeArray[1]);

							// Add temp to temperatureRes series data
							temperatureRes.series[0].data.push(item.temp);

							// Add humi to humidityRes series data
							humidityRes.series[0].data.push(item.humi);
						}

						// Now temperatureRes and humidityRes are populated with the required data
						this.temperatureData = temperatureRes;
						this.humidityData = humidityRes;
					},


				});
			},

			getServerData() {
				// 模拟从服务器获取数据时的延时
				setTimeout(() => {
					let temperatureRes = {
						categories: ["2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026",
							"2027"
						],
						series: [{
							name: "温度",
							data: [-21, 80, 95, 150, 112, 160, 95, 150, 112, 160, -21, 80, 95, 150,
								112, 160, 95, 150, 112, 160
							],
						}, ],
					};

					let humidityRes = {
						categories: ["2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026",
							"2027"
						],
						series: [{
							name: "湿度",
							data: [30, 40, 55, 60, 72, 80, 65, 60, 72, 80],
						}, ],
					};

					this.temperatureData = JSON.parse(JSON.stringify(temperatureRes));
					this.humidityData = JSON.parse(JSON.stringify(humidityRes));


				}, 500);
			},
			addNewData() {
				// 模拟加入新的数据
				const newTemperatureData = this.generateRandomData();
				const newHumidityData = this.generateRandomData();

				// 更新最新数据
				this.temperatureData.categories.push("New");
				this.temperatureData.series[0].data.push(...newTemperatureData);

				this.humidityData.categories.push("New");
				this.humidityData.series[0].data.push(...newHumidityData);
			},
			generateRandomData() {
				// 生成随机数据
				return Array.from({
					length: 1
				}, () => Math.floor(Math.random() * 100));
			},
		},
	};
</script>

<style scoped>
	/* 请根据实际需求修改父元素尺寸，组件自动识别宽高 */
	.charts-box {
		padding-top: 50rpx;
		width: 100%;
		height: 200px;
	}
</style>